package com.liuyi.netty.im.lychat.modular.caches;

import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.Cached;
import com.liuyi.netty.im.lychat.modular.entity.GroupMember;
import com.liuyi.netty.im.lychat.modular.enums.GroupRole;
import com.liuyi.netty.im.lychat.modular.service.IGroupMemberService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 群成员缓存
 *
 * @author Mr.Fmy
 * @since 2021/12/30
 */
@Service
public class GroupMemberCache {

    @Resource
    @Lazy
    private IGroupMemberService groupMemberService;

    @Cached(name = "GroupMember:", key = "'countByUserIdAndGroupId:'+#userId+':groupId:'+#groupId", timeUnit = TimeUnit.HOURS, expire = 4)
    public int countByUserIdAndGroupId(String userId, String groupId) {
        return groupMemberService.count(groupMemberService.q().eq(GroupMember.USER_ID, userId).eq(GroupMember.GROUP_NO, groupId));
    }

    @CacheInvalidate(name = "GroupMember:", key = "'countByUserIdAndGroupId:'+#userId+':groupId:'+#groupId")
    public void removeCountByUserIdAndGroupId(String userId, String groupId) {
    }

    @Cached(name = "GroupMember:", key = "'getByUserIdAndGroupId:'+#userId+':groupId:'+#groupId", timeUnit = TimeUnit.HOURS, expire = 4)
    public GroupMember getByUserIdAndGroupId(String userId, String groupId) {
        GroupMember groupMember = groupMemberService.getOne(groupMemberService.q().eq(GroupMember.USER_ID, userId).eq(GroupMember.GROUP_NO, groupId));
        groupMemberService.wrapper(groupMember);
        return groupMember;
    }

    @CacheInvalidate(name = "GroupMember:", key = "'getByUserIdAndGroupId:'+#userId+':groupId:'+#groupId")
    public void removeGetByUserIdAndGroupId(String userId, String groupId) {
    }

    @Cached(name = "GroupMember:", key = "'listByGroupId:'+#groupId", timeUnit = TimeUnit.HOURS, expire = 4)
    public List<GroupMember> listByGroupId(String groupId) {
        return groupMemberService.list(groupMemberService.q().eq(GroupMember.GROUP_NO, groupId));
    }

    @CacheInvalidate(name = "GroupMember:", key = "'listByGroupId:'+#groupId")
    public void removeListByGroupId(String groupId) {
    }


    /**
     * 群组管理员列表（群主+管理员）
     *
     * @param groupId 组id
     * @return {@link List}<{@link GroupMember}>
     */
    @Cached(name = "GroupMember:", key = "'listManageByGroupId:'+#groupId", timeUnit = TimeUnit.HOURS, expire = 4)
    public List<GroupMember> listManageByGroupId(String groupId) {
        return groupMemberService.list(groupMemberService.q().eq(GroupMember.GROUP_NO, groupId).between(GroupMember.GROUP_ROLE, GroupRole.MANAGE.getV(), GroupRole.ADMIN.getV()));
    }

    @CacheInvalidate(name = "GroupMember:", key = "'listManageByGroupId:'+#groupId")
    public void removeListManageByGroupId(String groupId) {
    }
}
